package cronjobs;

import helpers.DateHelper;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import data.AutoSiteData;

import models.AutoSiteModel;

public class CronAutoSiteLastestNews extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(CronAutoSiteLastestNews.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		log.setLevel(Level.FINE);
		response.setContentType("text/plain");
		AutoSiteData aData = new AutoSiteData();
		ArrayList<AutoSiteModel> sites = aData.getAll();
		AutoSiteModel site = new AutoSiteModel();
		for (int i = 0; i < sites.size(); i++) {
			site = sites.get(i);
//			if (!DateHelper.checkGreaterNow(site.getLastestScheduleSite(), site.getScheduleSite())) {
				Queue queue = QueueFactory.getDefaultQueue();
				String queueUrl = "/queue-lastest-news?url=" + URLEncoder.encode(site.getUrl());
				queue.add(TaskOptions.Builder.withUrl(queueUrl).method(Method.GET));
				log.info(queueUrl);
				response.getWriter().println("Cron lastest news success autoSite url: " + site.getUrl());
			/*} else {
				response.getWriter().println("Cron lastest news unsuccess autoSite id: " + site.getUrl());
			}*/
		}
	}
}
